<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>猜数字游戏</title>
		<!-- 引入jquery -->
		<!-- <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script> -->
		<script src="./jquery-3.7.0.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	
	<body>
		<div>
			<h2 align="center">猜数字游戏(1-10)</h2>
			<table align="center">
				<tr>
					<td>请输入你猜的数字:</td>
					<td><input type="text" name="in" style="width: 50px;" /> <button type="button" onclick="checkResult()">猜</button></td>
				</tr>
				<tr>
					<td>已猜次数:</td>
					<td align="center"><span id="times">0</span></td>
				</tr>
				<tr>
					<td>结果:</td>
					<td><span id="result"></span></td>
				</tr>
				<tr>
					<td colspan="2" align="center"><button type="button" onclick="reset()" style="width: 150px;">重开</button></td>
					<td></td>
				</tr>
			</table>
		</div>
		
		<script type="text/javascript">
			// 生成 1 - 10 之间的随机数
			var randomNum = Math.floor(Math.random()*10)+1;
			// 使用 jQuery 获取元素
			var result = jQuery("#result");
			var inputContent = jQuery("input");
			var count = jQuery("#times");
			
			function checkResult(){
				// 修改猜的次数
				var times = parseInt(jQuery("#times").text()) + 1;
				jQuery("#times").html(times);
				// 比对结果
				var guessNum = jQuery("input[name='in']").val();
				if(guessNum > randomNum) {
					result.html("猜大了！");
					result.css("color","red");
					inputContent.focus();
				} else if (guessNum < randomNum) {
					result.html("猜小了！");
					result.css("color","blue");
					inputContent.focus();
				} else {
					result.html("猜对了！");
					result.css("color","green");
				}
			}
			
			function reset(){
				// 重新生成随机数
				randomNum = Math.floor(Math.random()*10)+1;
				result.html("");
				count.html("0");
				inputContent.val("");
				inputContent.focus();
			}
		</script>
	</body>
</html>

